/**
 * 集成ext datagrid控件，实现datagrid和建模工具的集成，实现增，删，改，查的功能以及其他集成方式
 * 作者：xuqiang
 * 日期：2016-10-12
 * 版本：1.0
*/
Ext.namespace("Ext.com.bkfm")
Ext.define('Ext.com.bkfm.TreeDataGrid', {
	extend: "Ext.tree.Panel",
	//id : "grid_" + Ext.id(),
	//width : 400,
	//height : 300,
	autoScroll : false,
	//是否自动加载数据，默认为自动加载
	loadAuto: true,
	// 模板名称
	objPath : '',
	// 查询过滤条件 以 and 开始
	filter : '',
	//排序order by field asc
	orderby: '',
	// 默认列宽
	fieldWidth : 100,
	// 每页显示条数
	pageSize : 20,
	// 分页工具条,
	paging : false,
	// 是否显示行号
	showRowNum : false,
	// 是否显示复选框
	checked : true,
	//选择方式，multi,simple,single；默认为多选multi
	checkMode: 'single',
	//默认不现实根节点
	rootVisible: false,
	//根节点
	rootId: '',
	// 显示边框
	frame : true,//边框默认存在
	//隐藏的字段数组['FIELD']必须大写
	hiddenField: [],
	// 表单建模属性
	//columnMeta : null,
	// 存储表头信息
	columnHeaderMeta : null,
	// 表格数据映射记录
	columnFields : null,
	// 自定义列
	userConfigColumn : null,
	//是否可编辑，默认为不可编辑
	gridEditor: false,
	//初始化
	initComponent: function(){
		if(Ext.isEmpty(this.objPath)){
			AjaxUtils.showError('创建表格异常，无效的存储参数');
			Ext.com.bkfm.datagrid.superclass.initComponent.call(this);
			return;
		}

		this.getServiceModelMeta();
		this.callParent(arguments);
	},
	//获取服务器建模属性
	getServiceModelMeta: function(){
		var grid = this;
		AjaxUtils.CallJsonService({
			url: CONTEXT.contextPath+"/bkfm/metadata/v1/querytablemetacolumn",
			params: {
				"obj_path": grid.objPath
			},
			call: function(data){
				grid.createColumnMeta(data);
				grid.callSuperStrunct();
				//grid.addEditorPlugins();
			}
		});
	},
	callSuperStrunct: function(){
		//获取表格数据
		this.store = this.getGridStoreData();

		// 生成表格header头
		this.columns = this.columnHeaderMeta;

		//创建分页
		//this.paddingInfo();

	},
	//创建表格列属性
	createColumnMeta: function(data){
		var grid = this;
		//申明数组
		//this.columnMeta = new Array();
		this.columnHeaderMeta = new Array();
		this.columnFields = new Array();
		this.queryColumnField = {};
		// 判断是否需要显示行号
		if (this.showRowNum) {
			this.columnHeaderMeta.push(new Ext.grid.RowNumberer({
				width: 30
			}));
		}
		if(this.checked){
			var checkNum = 0;
			if(this.showRowNum){
				checkNum = 1;
			}
			//添加复选框
			var checkModel = Ext.create("Ext.selection.CheckboxModel", {
			    injectCheckbox: checkNum,//checkbox位于哪一列，默认值为0
			    mode: grid.checkMode,//multi,simple,single；默认为多选multi
			    checkOnly: false,//如果值为true，则只用点击checkbox列才能选中此条记录
			    allowDeselect: true,//如果值true，并且mode值为单选（single）时，可以通过点击checkbox取消对其的选择
			    enableKeyNav: true
			});
			this.selModel = checkModel;
		}
		for(i in data.entity){
			var columnData = data.entity[i];
			//获取列显示名称
			var columnName = columnData.zh_cn;
			//获取列对应的映射字段
			var columnMappingName = columnData.en_us;
			//获取列的显示宽度
			var columnWidth = parseInt(columnData.show_width || this.fieldWidth);

			var mappingDisplayField = this.parseUserConfig(columnMappingName,columnData.userConfig);
			var column = null;
			//判断是否可编辑
			/*var field = null;
			if(this.gridEditor){
				var field = grid.createEditorCell(columnData);
			}*/
			//判断是否可编辑
			var field = grid.createEditorCell(columnData);;
			/*if(this.gridEditor){
				var field = grid.createEditorCell(columnData);
			}*/
			//添加编辑框字段信息
			this.queryColumnField[columnMappingName] = field;

			if(mappingDisplayField !=null){
				/**
				 * 添加下拉树，选择节点字段
				 */
				column = {
						text : columnName,//表头显示名称
						fieldName: columnMappingName,//字段名称英文
						width : columnWidth,
						sortable : true,
						index : (i + 1) * 10,//索引序号
						dataIndex : columnMappingName+"_DISPLAYVALUE",//映射store中field字段
						hidden : false,
						editor: field
					};
			}else{
				//动态生成列
				column = {
					text : columnName,//表头显示名称
					fieldName: columnMappingName,//字段名称英文
					width : columnWidth,
					sortable : true,
					index : (i + 1) * 10,//索引序号
					dataIndex : columnMappingName,//映射store中field字段
					hidden : false,//是否需要隐藏字段显示
					editor: field
				};
			}
			if(i==0){
				//默认第一列为数节点可以展示下拉按钮
				column.xtype = 'treecolumn';
			}
			if(!Ext.isEmpty(column)){
				column = this.parseHiddenField(column);
				//添加映射数值列表
				this.columnHeaderMeta.push(column);
			}
			//存储字段列表到全局变量中
			this.columnFields.push(columnData);
			//存储建模属性
			//this.columnMeta.push(columnData);
		}
		//添加用户自定义列
		if(Ext.typeOf(this.userConfigColumn)=="array"){
			for(j in this.userConfigColumn){
				var index = this.userConfigColumn[j].index;
				//判断序号非越界数组，插入数组到指定位置
				if(index < this.columnHeaderMeta.length){
					//Utils.insertArray(index,this.userConfigColumn[j],this.columnHeaderMeta);
					Ext.Array.insert(this.columnHeaderMeta,index,this.userConfigColumn[j]);
				}else{
					//越界直接插入到数组的最后位置
					this.columnHeaderMeta.push(this.userConfigColumn[j]);
				}
			}
		}
	},
	/**
	 * 添加可编辑插件
	 */
	addEditorPlugins: function(){
		var grid = this;
		//判断是否可编辑
		if(this.gridEditor){
			var plugins = Ext.create('Ext.grid.plugin.CellEditing', {
				pluginId:'rowEditing',//必须定义可以通过该名称找到plugins
		        clicksToEdit : 1,
		        listeners : {
		            beforeedit : function(editor, e, eOpts) {
		                return true;
		            },
		            edit : function(editor, e) {
		            	//debugger;
		            	//alert(e.record.getId());
		            	var id = e.column.getEditor().fieldId;
		            	//id = id.substr(id.indexOf("_")+1);
		            	var name = e.column.getEditor().getName();
		            	var xtype = e.column.getEditor().getXType();
		            	if(xtype=="select" || xtype=="tree"){
		            		//debugger;
		            		e.record.set(id+"_DISPLAYVALUE", e.column.getEditor().getDisplayValue());
			                e.record.set(id, e.column.getEditor().getValue());
		            	}else if(xtype=="datefield"){
		    				e.record.set(id,e.column.getEditor().getRawValue());
		            	}else{
		            		e.record.set(id, e.column.getEditor().getValue());
		            	}
		            	//debugger;
		                //设置记录状态为修改
		            	if(Ext.isEmpty(e.record.getId())){
		            		e.record.state = Constants.RECORD_NEW;
		            	}else{
		            		e.record.state = Constants.RECORD_CHANGED;
		            	}

		            }
		        }
		    });
			//this.plugins = plugins;
			this.addPlugin(plugins);
		}
	},
	/***
	 * 创建可编辑单元格
	 * 用于用户设置单元格可编辑时操作,返回具体的操作字段
	 */
	createEditorCell: function(metaField){
		var form = this;
		var field = null;
		var allowBlank = true;
		if(metaField.is_primary_key == Constants.YES){
			//必填
			allowBlank = false;
		}else if(metaField.is_empty == Constants.NO){
			//必填
			allowBlank = false;
		}else{
			//非必填
			allowBlank = true;
		}
		//防止可编辑框的表单id和其他表单重复，默认加上当前的grid编码，获取数据时也需要带上该编码
		var fieldId = metaField.enName;
		if(Ext.isEmpty(metaField.userConfig)){
			field = Ext.create('Ext.form.field.Text',{
				fieldId: fieldId,
				allowBlank: allowBlank
			});
		}else{
			var config = Ext.JSON.decode(metaField.user_config);
			var ftype = config.ftype;
			var required = config.required || false;
			if(required){
				//必填
				allowBlank = false;
			}
			switch(ftype){
				case Constants.FIELDSELECT:{
						//判断该字段是否有动态关联字段
						var linkage = config.linkage || false;
						//动态关联字段
						var linkagefield = config.linkagefield || "";
						//动态关联字段的查询字段
						var linkagefilterfield = config.linkagefilterfield || "";

						field = Ext.create("Ext.com.bkfm.combobox",{
							fieldId: fieldId,
							allowBlank: allowBlank,
							editable: false,
							objPath: metaField.obj_path,
							loadingText:'加载中……'
						});
					break;
				}
				case Constants.FIELDDATE:{
					field = Ext.create('Ext.form.field.Date',{
						fieldId: fieldId,
						allowBlank: allowBlank,
						format: config.format || 'Y-m-d'
					});
					break;
				}
				case Constants.FIELDNUMBER:{
					field = Ext.create('Ext.form.field.Number',{
						fieldId: fieldId,
						allowBlank: allowBlank,
						hideTrigger: true,
				        keyNavEnabled: false,
				        mouseWheelEnabled: false
					});
					break;
				}
				case Constants.FIELDPASSWORD:{
					field = Ext.create('Ext.form.field.Text',{
						fieldId: fieldId,
						allowBlank: allowBlank,
						inputType: 'password'
					});
					break;
				}
				case Constants.FIELDCHECKBOX:{
					field = Ext.create('Ext.form.field.Checkbox',{
						fieldId: fieldId,
						allowBlank: allowBlank
					});
					break;
				}
				case Constants.FIELDTREE:{
					 field = Ext.create("Ext.com.bkfm.comboboxtree", {
						 	fieldId: fieldId,
					        //cascade : 'parent',//级联方式:1.child子级联;2.parent,父级联,3,both全部级联
					        checkModel:'single',//当json数据为不带checked的数据时只配置为single,带checked配置为double为单选,不配置为多选
					        treeConfigId: config.treeConfigId,
					        rootId: config.rootTreeId,
					        treeNodeParameter : {

					        }
					    });
					break;
				}
				default:{
					field = Ext.create('Ext.form.field.Text',{
						id: fieldId,
						allowBlank: allowBlank
					});
					break;
				}
			}
		}
		return field;
	},
	//获取表格数据
	getGridStoreData : function() {
		var grid = this;

		//定义Ext.data.Model fields数组
		var fields = new Array();
		//alert("长度"+fields.length);
		for(i in this.columnFields){
			var meta = this.columnFields[i];
			//debugger;
			fields.push(this.createDataModel(meta));
			//判断是否为下拉的键值对应关系，如果是则添加键值转换列
			var mappingDisplayField = this.parseUserConfig(meta.enName,meta.userConfig);
			if(mappingDisplayField !=null){
				fields.push(mappingDisplayField);
			}
		}

		//定义Ext.data.Model id名称
		var modelId = this.id+"_data_model";
		//alert(modelId);
		//定义grid的model列
		this.modelField = Ext.define(modelId, {
	        extend: 'Ext.data.Model',
	        fields: fields
	    });

		var proxy_url = CONTEXT.contextPath + "/model/v1/getTreeDataGridMeta";
		var store =  Ext.create('Ext.data.TreeStore', {
            model: modelId,
            proxy: {
                type: 'ajax',
                url: proxy_url,
                getMethod: function(){
	            	return 'post';
	            },
				reader: {
					type: 'json',
					idProperty: 'RWID',
	                root: 'list',
	                totalProperty: 'total'
	            },
                //传参
                extraParams : {
                	objPath : grid.objPath, // 建模对象
    				filter : grid.filter,
    				orderby: grid.orderby,
    				limit: grid.pageSize,
    				paging: grid.paging
                }
            },
            autoLoad: true,
            rootVisible: false,
            root: {
                expanded: true,
                id: grid.rootId || '-1'
            },
            listeners: {
            	'beforeexpand' : function(store,node,eOpts){
                    //点击父亲节点的菜单会将节点的id通过ajax请求，将到后台
            		grid.setSelectNodeId(store.get("id"));
                 },
                 'beforeload': function(store,operation,eOpts){
 	            	//debugger;
                	 this.proxy.extraParams.parentId = (operation.id|| '-1');
 	            	this.proxy.extraParams.filter = "and parentId='"+(operation.id|| '-1')+"'";
 	            },
				load: function () {
				  /*var rootnode = grid.getRootNode();

				  console.log(grid.getRootNode());

				  if (rootnode.childNodes.length > 0) {
				      //rootnode.childNodes[0].expand();
				  }*/
				}
            }
		});
		return store;
	},
	//创建store的字段类型
	createDataModel: function(meta){
		var fieldConfig = {
				name: meta.enName,
				mapping: meta.enName
		};
		var userConfig = Ext.JSON.decode(meta.user_config || "{}");
		switch(meta.modelField){
			case '1':{
				fieldConfig.type = "string";
				//字符串日期
				if(userConfig.ftype=="date"){
					fieldConfig.convert = function(value){
						if(Ext.isEmpty(value)){
							return "";
						}else{
							//debugger;
							var date = new Date(Date.parse(value.replace(/-/g, "/")));
							var createTime = Ext.Date.format(date,userConfig.format || "Y-m-d");
							return createTime;
						}

			         } ;
				}
				break;
			}
			case '2':{
				fieldConfig.type = "number";
				break;
			}
			case '3':{
				fieldConfig.type = "date";
				//日期格式化为年月日，时分秒
				fieldConfig.convert = function(value){
					if(Ext.isEmpty(value)){
						return "";
					}else{
						var date = new Date(Date.parse(value.replace(/-/g, "/")));
						var createTime = Ext.Date.format(date,userConfig.format || "Y-m-d");
						return createTime;
					}

		         } ;
				break;
			}
			case '4':{
				fieldConfig.type = "float";
				break;
			}
			default:{
				fieldConfig.type = "string";
				break;
			}
		}
		return fieldConfig;
	},
	//创建分页工具栏
	paddingInfo: function(){
		if(this.paging){
			var grid = this;
			var bbar = Ext.create('Ext.PagingToolbar', {
	            pageSize: grid.pageSize,
	            store: grid.store,
	            displayInfo: true,
	            beforePageText: '第',
				afterPageText : "页,共{0}页",
				firstText : "第1页",
				prevText : "上一页",
				nextText : "下一页",
				lastText : "最后一页",
				refreshText : "刷新",
	            displayMsg: '显示第 <font color=red>{0}</font> 条到 <font color=red>{1}</font> 条记录，一共<font color=red> {2}</font> 条',
	            emptyMsg: "暂无数据"
	        })
	        this.pageToolBar = bbar;
			this.bbar = bbar;
		}
	},
	//处理用户自定义配置信息,解析用户字段为下拉配置时的映射关系
	parseUserConfig: function(enname,userConfig){
		if(Ext.isEmpty(userConfig)){
			return null;
		}
		var config = Ext.JSON.decode(userConfig);
		var ftype = config.ftype;

		if(ftype==Constants.FIELDSELECT || ftype==Constants.FIELDTREE){
			var fieldConfig = {
					name: enname+"_DISPLAYVALUE",
					mapping: enname+"_DISPLAYVALUE",
					type: 'string'
			};
			return fieldConfig;
		}

		return null;

	},
	/**
	 * 转换表格字段，设置表格的每一列是否需要隐藏
	 * field: 表格列
	 */
	parseHiddenField: function(field){
		var name = field.fieldName;
		if(!Ext.isEmpty(this.hiddenField)){
			if(Ext.Array.contains(this.hiddenField,name)){
				field.hidden = true;
			}
		}
		return field;
	},
	/**
	 * 根据记录id选中记录行
	 */
	selectRecordById: function(id){
		var record = this.getStore().getById(id);
		if(record){
			this.getSelectionModel().select(record.index,true);
		}
	},
	/**
	 * 根据记录索引行号选中记录行
	 */
	selectRecordByIndex: function(index){
		this.getSelectionModel().select(index,true);
	},
	//获取当前选中记录
	getSelectedRecords: function(){
		var records = this.getSelectionModel().getSelection();
		return records;
	},
	//获取选中记录id
	getRecordId: function(record){
		if(record){
			return record.getId();
		}
		AjaxUtils.showError('无效的记录参数值');
		return "";
	},
	//设置选中节点的id值
	setSelectNodeId: function(id){
		this.selectNodeId = id;
	},
	//获取选中或者展开节点的id
	getSelectNodeId: function(){
		return this.selectNodeId;
	},
	//获取选中节点
	getSelectNode: function(){
		var node = this.getSelectionModel().selected;
		//debugger;
		if(node && node.items && node.items.length >0){
			return node.items[0];
		}else{
			if(!Ext.isEmpty(this.getSelectNodeId())){
				return this.store.getNodeById(this.getSelectNodeId());
			}
		}

		//返回根目录节点，
		return this.getRootNode();
	},
	/**
	 * 获取选中节点的父节点,不存在则返回根节点
	 */
	getSelectParentNode: function(){
		return this.getSelectNode().parentNode || this.getRootNode()
	},
	/**
	 * 获取grid修改的数据
	 */
	getModifiedRecords: function(){
		if(this.gridEditor){
			return this.getStore().getModifiedRecords();
		}else{
			console.log("当前grid不可编辑，无法获取修改数据记录");
			return null;
		}

	},
	/**
	 * 设置全局查询条件
	 */
	setFilter: function(filter){
		this.filter = filter;
		this.getStore().baseParams.filter = this.filter;
		Ext.apply(this.getStore().proxy.extraParams, this.getStore().baseParams);
	},
	/**
	 * 获取全局查询条件
	 */
	getFilter: function(){
		return this.filter;
	},
	/**
	 * 保存修改的数据
	 * callback 回调函数
	 */
	save: function(callback){
		if(!this.gridEditor){
			AjaxUtils.showError('非可编辑表格，无效的操作权限');
			return;
		}
		var records = this.getModifiedRecords();
		if(!records || records.length ==0){
			AjaxUtils.showError('无修改数据记录');
			return;
		}

		var savePath = this.objPath;
		if(!Ext.isEmpty(this.saveObjPath)){
			savePath = this.saveObjPath;
		}

		var grid = this;
		var submitRecord = new Array();
		var isvalid = true;
		Ext.each(records, function(item, rowindex) {
			var rwid = item.getId();
			if(Ext.isEmpty(rwid) || item.state == Constants.RECORD_NEW){
				//新纪录或者rwid为空
				rwid = Utils.getRwid();
			}
			submitRecord.push({
				"obj_path": savePath,
				"record_state": item.state,
				"rwid": rwid,
				"record_data": Ext.JSON.encode(item.data)
			});
			for(i in grid.columnHeaderMeta){
				var col = grid.columnHeaderMeta[i];
				if(col.required_field){
					var col_name = col.fieldName;
					var col_dis_name = col.text;
					if(!col.allowBlank && Ext.isEmpty(item.data[col_name])){
						AjaxUtils.showError('表单第'+(rowindex+1)+'行，【'+col_dis_name+'】,不可为空');
						isvalid = false;
						return false;
					}
				}
			}
		});
		if(!isvalid){
			return ;
		}

		AjaxUtils.CallService({
			url: CONTEXT.contextPath+"/bkfm/metadata/v1/savemodelmetadata",
			dataType: "json",
			params: submitRecord,
			call: function(data){
				if(Ext.isFunction(callback)){
					callback(data);
				}else{
					if(data.status == "OK"){
						/*AjaxUtils.showInfo('操作成功',function(){
							grid.reload();
						});*/
						grid.reload();
					}else{
						AjaxUtils.showError('操作失败');
					}
				}

			}
		});

	},
	/**
	 * 新建一条空记录
	 * @callback 回调函数，参数为新建的行记录
	 */
	addNewRecord: function(callback){
		if(!this.gridEditor){
			AjaxUtils.showError('非可编辑表格，无效的操作权限');
			return;
		}
		var record = Ext.create(this.modelField,{});
		//设置记录状态为新增
		record.state = Constants.RECORD_NEW;
		this.getStore().insert(0,record);
		var rowEditing = this.getPlugin("rowEditing");
		rowEditing.startEdit(0,0);
		if(Ext.isFunction(callback)){
			callback(record);
		}
	},
	/**
	 * 删除选择记录
	 * @param {} callback 回调函数
	 */
	deleteRecords: function(fatherFieldName,callback){
		var selNode = this.getSelectedRecords()[0];
		if(Ext.isEmpty(selNode)){
			return;
		}

		/*if(Ext.isEmpty(this.objPath)){
			AjaxUtils.showError("业务建模路径为配置，不可删除");
			return;
		}*/
		var tree = this;
		var del_param = new Array();
		for(i in records){
			var r = records[i];
			if(r.getId()){
				del_param.push({
					"obj_path": tree.objPath,
					"rwid": r.getId()
				})
			}else{
				this.getStore().remove(r);
			}

		}
		//判断是否需要远程删除
		if(Ext.isEmpty(del_param)){
			return;
		}

		Ext.Msg.confirm("系统提示","确定需要删除所选节点及其子节点？删除后将不可恢复!",function(btn){
			if(btn =="yes"){
				AjaxUtils.CallService({
					url: CONTEXT.contextPath+"/bkfm/metadata/v1/delmodelmetadata",
					dataType: "json",
					params: del_param,
					call: function(data){
						debugger;
						if(data.status=='OK'){
							AjaxUtils.showInfo('操作成功',function(){
								debugger;
								var node  = tree.getSelectNode();
								var parentNode = node;

								//判断当前选择的节点是否为根节点
								if(node.get("id")!="-1"){
									//不是根节点则获取父节点刷新
									parentNode = node.parentNode;
								}
								if(Ext.isFunction(callback)){
									Ext.callback(callback, this, data);
								}
								tree.reloadSelectNode(parentNode);
							});

						}else{
							AjaxUtils.showError('操作失败',function(){
								if(Ext.isFunction(callback)){
									Ext.callback(callback, this, data);
								}
							});
						}
					}
				});
			}
		});
	},
	/**
	 * 导入查询结果
	 */
	importGridData: function(){
		AjaxUtils.showInfo('正在完善中');
	},
	/**
	 * excel文件导出
	 */
	exportGridDate: function(){
		AjaxUtils.showInfo('正在完善中');
	},
	/**
	 * 刷新grid列表
	 */
	reload: function(){
		this.getStore().load();
	},
	/**
	 * 刷新节点，refreshNode 节点存在则直接刷新传入节点，否则刷新当前选中的节点
	 * selNode 刷新成功后需要选择的节点
	 */
	reloadSelectNode: function(refreshNode){
		debugger;
		var node = refreshNode || this.getSelectNode();
		if(node.isExpanded()){
			node.store.load({
				node: node
			});
		}else{
			node.expand();
		}

	},
	/**
	 * 重新查询
	 * 在原有的查询条件下再次追加条件进行查询
	 * @paramsFilter 查询条件sql语句
	 */
	search: function(paramsFilter){
		if(Ext.isEmpty(paramsFilter)){
			this.reload();
		}else{
			this.getStore().load({
				params : {
					appendFilter : paramsFilter
				}
			});
		}
	},
	/**
	 * 打开自定义查询窗体
	 */
	customizeQuery: function(){
		var super_grid = this;
		if(this.query_win){
			this.query_win.show();
			return;
		}
		
	    Ext.define('State', {  
	        extend: 'Ext.data.Model',  
	        fields: [  
	            {name: 'value' },  
	            {name: 'text' }  
	        ]  
	    });  
	    //查询规则
	    var rule_combo = Ext.create('Ext.form.field.ComboBox', {
	    	displayField: 'text',
	        valueField: 'value',
	        store: Ext.create('Ext.data.Store', {  
			        model: 'State',  
			        data: [  
				        { "value": "AND", "text": "AND"},  
				        { "value": "OR", "text": "OR"}
				    ]
		    }),  
	        queryMode: 'local',
	        editable: false
	    });
	    //查询方式  
	    var expression_combo = Ext.create('Ext.form.field.ComboBox', {  
	    	displayField: 'text',
	        valueField: 'value', 
	        store: Ext.create('Ext.data.Store', {  
			        model: 'State',  
			        data: [  
				        { "value": "=", "text": "="},  
				        { "value": ">", "text": ">"},
				        { "value": ">=", "text": ">="},
				        { "value": "<", "text": "<"},
				        { "value": "<=", "text": "<="},
				        { "value": "LIKE", "text": "LIKE"},
				        { "value": "<>", "text": "<>"}
				    ]
		    }),  
	        queryMode: 'local',  
	        typeAhead: true,
	        editable: false
	    });
	    //查询字段
	    var fieldlist = new Array();
	    for(i in this.columnHeaderMeta){
	    	var field = this.columnHeaderMeta[i];
	    	if(!field.fieldName){
	    		continue;
	    	}
	    	fieldlist.push({
	    		"value": field.fieldName,
	    		"text": field.text
	    	});
	    	
	    }
	    var field_combo = Ext.create('Ext.form.field.ComboBox', {  
	    	displayField: 'text',
	        valueField: 'value', 
	        store: Ext.create('Ext.data.Store', {  
			        model: 'State',  
			        data: fieldlist,
			        fields: ['value', 'text']
		    }),
		    id: "combo_field",
		    name: "combo_field",
	        queryMode: 'local',  
	        typeAhead: true,
	        editable: false
	    });
	    
	    //创建表格  
	    var queryGridPanel = new Ext.grid.GridPanel({  
	        autoHeight:true,  
	        store: new Ext.data.ArrayStore({  
		        data: [],  
		        fields:[{name:'rule'},  
		           {name:'field'},
		           {name:'field_display'},
		           {name:'expression'},
		           {name:'field_value'},
		           {name:'field_value_display'}
		        ]  
		    }),  
		    selModel: Ext.create("Ext.selection.CheckboxModel", {
			    injectCheckbox: 1,//checkbox位于哪一列，默认值为0
			    mode: "multi",//multi,simple,single；默认为多选multi
			    checkOnly: false,//如果值为true，则只用点击checkbox列才能选中此条记录
			    allowDeselect: true,//如果值true，并且mode值为单选（single）时，可以通过点击checkbox取消对其的选择
			    enableKeyNav: true
			}),
	        columns: [new Ext.grid.RowNumberer({width:30}),
	        	{header:'规则',dataIndex:'rule',width:150,editor:rule_combo},
	        	{header:'查询字段',dataIndex:'field_display',width:150,editor:field_combo},
	        	{header:'表达式',dataIndex:'expression',width:150,editor:expression_combo},
	        	{header:'查询值',dataIndex:'field_value_display',width:150,editor:true}
	        	], 
	        listeners:{
	        	beforeedit: function (editor, e, eOpts){
	        	},
	        	edit : function(editor, e) {
	        		if(e.colIdx == 5){
	        			//查询值
		            	var xtype = e.column.getEditor().getXType();
		            	if(xtype=="select"){
		            		e.record.set("field_value",e.column.getEditor().getValue());
		            		e.record.set("field_value_display", e.column.getEditor().getDisplayValue());
		            	}else if(xtype=="tree"){
		            		e.record.set("field_value",e.column.getEditor().getValue());
		            		e.record.set("field_value_display", e.column.getEditor().getDisplayValue());
		            	}else if(xtype=="datefield"){
		    				e.record.set("field_value",e.column.getEditor().getValue());
		    				e.record.set("field_value_display",e.column.getEditor().getRawValue());
		            	}else{
		            		e.record.set("field_value", e.column.getEditor().getValue());
		            		e.record.set("field_value_display", e.column.getEditor().getValue());
		            	}
	        		}else if(e.colIdx == 3){
	        			//字段名
	        			e.record.set("field",e.column.getEditor().getValue());
	            		e.record.set("field_display", e.column.getEditor().getDisplayValue());
	            		
	            		//
	            		var record = queryGridPanel.getStore().getAt(e.rowIdx);
	        			var column_field = record.get("field");
	        			if(!record.isCreatEditor || record.editorField !=column_field){
	        				var col = queryGridPanel.columnManager.getColumns()[5];
	        				var field_box = super_grid.queryColumnField[column_field];
	        				var xtype = field_box.getXType();
	        				var field = null;
	        				if(xtype == 'select'){
	        					field = Ext.create("Ext.com.bkfm.combobox",{
        							objPath: field_box.objPath,
        							type: 'objPath',
        							loadingText:'加载中……',
        							editable: false
        						});
	        				}else if(xtype == 'datefield'){
	        					field = Ext.create('Ext.form.field.Date',{
	        						format: field_box.format,
	        						editable: false
	        					});
	        				}else if(xtype == 'tree'){
	        					field = Ext.create("Ext.com.bkfm.comboboxtree", {
        					        checkModel:'single',
        					        treeConfigId: field_box.treeConfigId,
        					        rootId: field_box.rootId,
        					        treeNodeParameter : {

        					        },
        					        editable: false
        					    });
	        				}else{
	        					field = Ext.create('Ext.form.field.Text',{
	        					});
	        				}
	        				col.setEditor(field);
		        			record.isCreatEditor = true;
		        			record.editorField = column_field;
		        			e.record.set("field_value", "");
		            		e.record.set("field_value_display", "");
	        			}
	        		}
	            }
	        },
	        selType: 'cellmodel',  
	        plugins:[  
	                 Ext.create('Ext.grid.plugin.CellEditing',{  
	                     clicksToEdit:1 //设置单击单元格编辑  
	                 })  
	        ],  
	        tbar:['-',{  
	            text:'添加',  
	            iconCls: 'add',
	            handler:function(){  
	                var p ={  
	                        id:'',  
	                        name:'',  
	                        descn:''  
	                        }; 
	                	var store = queryGridPanel.getStore();
	                    store.insert(store.getCount(),p);  
	                }  
	            },'-',{  
	                text:'删除',  
	                iconCls: 'delete',
	                handler:function(){  
	                    Ext.Msg.confirm('系统提示','确定要删除？',function(btn){  
	                        if(btn=='yes'){  
	                        	 var store = queryGridPanel.getStore();
	                        	var records = queryGridPanel.getSelectionModel().getSelection();
	                        	for(i in records){
	                        		var record = records[i];
	                        		store.remove(record);
	                        	}
	                        }  
	                    });  
	                }  
	        },'-',{
	        	text: '查询',
	        	iconCls: 'search',
	        	handler: function(){
	        		var records =  queryGridPanel.getStore().getModifiedRecords();
	        		var filter = "";
	        		for(i in records){
	        			var record = records[i];
	        			var rule = record.get("rule");
	        			var field_value = record.get("field");
	        			var expression = record.get("expression");
	        			var field_value_display = record.get("field_value_display");
	        			if(i==0){
	        				rule = "";
	        			}
	        			if(expression == 'LIKE'){
	        				filter += rule + " "+field_value+ " "+expression+" '%"+field_value_display+"%' ";
	        			}else{
	        				filter += rule + " "+field_value+ " "+expression+" '"+field_value_display+"' ";
	        			}
	        		}
	        		super_grid.search(filter);
	        		super_grid.query_win.close();
	        	}
	        }]  
	    });
	    
		this.query_win = Ext.create('Ext.com.bkfm.window', {
		    title: '高级查询',
		    autoScroll : true,
			modal : true,
		    height : Utils.getHeight()/2,
			width : Utils.getWidth()/2,
		    closeAction: 'hide',
		    items: queryGridPanel
		}).show(); 
	}
});